/**
 * Created by linyh on 2017/1/9 0009.
 */

window.FileAPI = {
    debug: true,
    cors: false,
    // expando: '123123',
    withCredentials: false,
};
var FileApi = require("file-api");
FileApi.withCredentials = false;

var $uploadInput = $('<input type="file" style="visibility:hidden;" id="_ef">').appendTo('body');
function chooseFile() {
    $uploadInput.click();
}

var token = '';
JxSdk.sundry.uploadToken().then(function(data) {
    token = data.uptoken;
});

function Uploader(files, options) {
    this.files = files || [];

    var _self = this;
    FileApi.event.on($uploadInput[0], 'change', function (evt/**Event*/){
        var files = FileApi.getFiles(evt);
        var xhr = FileApi.upload({
            url: 'http://upload.qiniu.com',
            data: { 'token': token },
            files: { file: files[0] },
            complete: function (err, xhr){
                if( !err ){
                    var result = xhr.responseText;

                    var info = JSON.parse(result);
                    _self.files.push(info.data);
                }
            }
        });
    });
}

Uploader.prototype.chooseFile = function() {
    chooseFile();
};

module.exports = Uploader;